﻿using DevExpress.Internal;
using DevExpress.XtraEditors;
using DevExpress.XtraPrinting;
using MesProjectWinform.Public;
using MesProjectWinform.Public.Common;
using MesProjectWinform.WareHouse.Entity;
using MesProjectWinform.WareHouse.Form.库位;
using MesProjectWinform.用户控件;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MesProjectWinform.WareHouse.Form.数据维护
{
    public partial class Form_Emp : DevExpress.XtraEditors.XtraForm
    {
        private PaginationControl paginationControl;
        private int currentPage = 1;
        private int pageSize = 10;

        public Form_Emp()
        {
            InitializeComponent();
            InitializePagination();
        }

        /// <summary>
        /// 初始化分页控件
        /// </summary>
        private void InitializePagination()
        {
            // 创建分页控件
            paginationControl = new PaginationControl();
            paginationControl.Dock = DockStyle.Bottom;

            // 设置分页控件的属性
            paginationControl.PageSize = pageSize;
            paginationControl.CurrentPage = currentPage;
            paginationControl.PageSizeOptions = new List<int> { 5, 10, 20, 50, 100 };

            // 添加事件处理器
            paginationControl.PageChanged += PaginationControl_PageChanged;
            paginationControl.PageSizeChanged += PaginationControl_PageSizeChanged;

            // 将分页控件添加到窗体
            panelControl3.Controls.Add(paginationControl);
        }

        private void PaginationControl_PageChanged(object sender, PageChangedEventArgs e)
        {
            currentPage = e.CurrentPage;
            pageSize = e.PageSize;
            LoadData();
        }

        private void PaginationControl_PageSizeChanged(object sender, PageSizeChangedEventArgs e)
        {
            currentPage = e.CurrentPage;
            pageSize = e.PageSize;
            LoadData();
        }

        private void Form_Emp_Load(object sender, EventArgs e)
        {
            LoadData();
        }

        private void BtnQry_Click(object sender, EventArgs e)
        {
            currentPage = 1;
            if (paginationControl != null)
            {
                paginationControl.CurrentPage = 1;
            }
            LoadData();
        }

        private void BtnAdd_Click(object sender, EventArgs e)
        {

            try
            {
                // 创建新增窗体
                Form_AddEmp from = new Form_AddEmp();
                from.UpdateType = true;

                // 显示窗体并处理结果
                if (from.ShowDialog() == DialogResult.OK)
                {
                    // 新增成功后刷新数据
                    Clear();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("打开新增窗体时发生错误：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void BtnClear_Click(object sender, EventArgs e)
        {
            // 清空查询条件
            TxtCode.Text = string.Empty;
            TxtName.Text = string.Empty;
        }

        private void BtnExport_Click(object sender, EventArgs e)
        {
            try
            {
                // 创建保存对话框
                SaveFileDialog saveDialog = new SaveFileDialog();
                saveDialog.Filter = "Excel文件|*.xlsx|Excel 97-2003|*.xls";
                saveDialog.Title = "导出Excel";
                saveDialog.FileName = "人员信息" + DateTime.Now.ToString("yyyyMMddHHmmss");
                saveDialog.RestoreDirectory = true;

                if (saveDialog.ShowDialog() == DialogResult.OK)
                {
                    // 显示等待提示
                    Cursor = Cursors.WaitCursor;

                    // 根据文件扩展名选择导出格式
                    string extension = Path.GetExtension(saveDialog.FileName).ToLower();

                    if (extension == ".xlsx")
                    {
                        // 导出为XLSX格式
                        ExportToExcelAdvanced(saveDialog.FileName, true);
                    }
                    else if (extension == ".xls")
                    {
                        // 导出为XLS格式
                        ExportToExcelAdvanced(saveDialog.FileName, false);
                    }

                    // 恢复光标
                    Cursor = Cursors.Default;

                    // 询问是否打开文件
                    if (MessageBox.Show("导出成功，是否立即打开？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                    {
                        System.Diagnostics.Process.Start(saveDialog.FileName);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("导出Excel时发生错误：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                // 恢复光标
                Cursor = Cursors.Default;
            }
        }

        #region 自定义方法
        /// <summary>
        /// 导出Excel的高级方法，支持自定义设置
        /// </summary>
        /// <param name="filePath">文件保存路径</param>
        /// <param name="isXlsx">是否为XLSX格式</param>
        private void ExportToExcelAdvanced(string filePath, bool isXlsx)
        {
            try
            {
                // 检查数据源是否为空
                DataTable dataSource = gridControl1.DataSource as DataTable;
                if (dataSource == null || dataSource.Rows.Count == 0)
                {
                    MessageBox.Show("没有数据可导出，请先查询数据。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                if (isXlsx)
                {
                    // 创建XLSX导出选项
                    XlsxExportOptionsEx options = new XlsxExportOptionsEx();

                    // 设置导出选项
                    options.ExportType = DevExpress.Export.ExportType.WYSIWYG; // 所见即所得
                    options.SheetName = "人员信息"; // 设置工作表名称
                    options.TextExportMode = TextExportMode.Value; // 导出值而不是显示文本

                    // 设置标题和页眉
                    options.ExportHyperlinks = true; // 导出超链接
                    options.ShowGridLines = true; // 显示网格线

                    // 导出到Excel
                    gridControl1.ExportToXlsx(filePath, options);
                }
                else
                {
                    // 创建XLS导出选项
                    XlsExportOptionsEx options = new XlsExportOptionsEx();

                    // 设置导出选项
                    options.ExportType = DevExpress.Export.ExportType.WYSIWYG; // 所见即所得
                    options.SheetName = "人员信息"; // 设置工作表名称
                    options.TextExportMode = TextExportMode.Value; // 导出值而不是显示文本

                    // 设置标题和页眉
                    options.ExportHyperlinks = true; // 导出超链接
                    options.ShowGridLines = true; // 显示网格线

                    // 导出到Excel
                    gridControl1.ExportToXls(filePath, options);
                }
            }
            catch (IOException ioEx)
            {
                MessageBox.Show("导出Excel时发生I/O错误：" + ioEx.Message + "\n可能是文件被占用或没有写入权限。",
                               "I/O错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception ex)
            {
                MessageBox.Show("导出Excel时发生错误：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        /// <summary>
        /// 清空搜索条件并刷新数据
        /// </summary>
        public void Clear()
        {
            try
            {
                // 显示等待光标
                Cursor = Cursors.WaitCursor;

                // 清空搜索框
                TxtCode.Text = "";
                TxtName.Text = "";
                // 重置为第一页
                currentPage = 1;
                if (paginationControl != null)
                {
                    paginationControl.CurrentPage = 1;
                }

                // 重新加载数据
                LoadData();
            }
            catch (Exception ex)
            {
                MessageBox.Show("刷新数据时发生错误：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                // 恢复光标
                Cursor = Cursors.Default;
            }
        }
        /// <summary>
        /// 加载数据
        /// </summary>
        private async void LoadData()
        {
            try
            {
                // 禁用分页控件，防止重复操作
                if (paginationControl != null)
                {
                    paginationControl.Enabled = false;
                }

                // 显示等待光标
                Cursor = Cursors.WaitCursor;

                string action;

                // 对查询参数进行URL编码，避免特殊字符问题
                string encodedCode = Uri.EscapeDataString(TxtCode.Text.Trim());
                string encodedName = Uri.EscapeDataString(TxtName.Text.Trim());
                action = $"WareHouse/Emp/GetEMP?pageNum={currentPage}&pageSize={pageSize}&QryID={encodedCode}&QryName={encodedName}";

                // 调用API
                string json = await HttpClientHelper.RequestUrl(RequestType.Get, action, null);
                ApiPaging<List<EMP>> model = JsonConvert.DeserializeObject<ApiPaging<List<EMP>>>(json);

                // 使用安全的UI更新方式
                UpdateUIWithData(model);
            }
            catch (Exception ex)
            {
                MessageBox.Show("执行查询时发生错误：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                // 恢复光标
                Cursor = Cursors.Default;

                // 确保分页控件可用
                if (paginationControl != null)
                {
                    paginationControl.Enabled = true;
                }
            }
        }

        /// <summary>
        /// 更新UI界面数据
        /// </summary>
        /// <param name="model">API返回的数据模型</param>
        private void UpdateUIWithData(ApiPaging<List<EMP>> model)
        {
            // 检查是否在UI线程上，如果不是则使用Invoke
            if (InvokeRequired)
            {
                Invoke(new Action<ApiPaging<List<EMP>>>(UpdateUIWithData), model);
                return;
            }

            if (model != null && model.Code==ApiEnums.Success)
            {
                // 绑定数据到GridControl
                gridControl1.DataSource = model.Data;

                // 更新分页控件
                if (paginationControl != null)
                {
                    paginationControl.TotalRecords = model.TotalCount;
                    paginationControl.CurrentPage = currentPage;
                    paginationControl.PageSize = pageSize;
                }
            }
            else
            {
                // 显示错误信息
                MessageBox.Show($"获取数据失败: {model?.Message ?? "未知错误"}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                
                // 清空数据源
                gridControl1.DataSource = null;
                
                // 设置分页控件为0条记录
                if (paginationControl != null)
                {
                    paginationControl.TotalRecords = 0;
                }
            }
        }
        #endregion

        private async void DeleteBtn_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            try
            {
                if (gridView1.FocusedRowHandle >= 0)
                {
                    // 获取当前选中行的数据
                    var focusedRow = gridView1.GetFocusedRow();
                    if (focusedRow == null)
                    {
                        MessageBox.Show("无法获取选中行的数据", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                    // 获取当前选中行的货架名称和ID
                    //DataRow row = gridView1.GetFocusedDataRow();
                    string EmpID = focusedRow.GetType().GetProperty("EMPID")?.GetValue(focusedRow)?.ToString();
                    string EMPNAME = focusedRow.GetType().GetProperty("EMPName")?.GetValue(focusedRow)?.ToString() ?? "未命名员工";

                    // 显示确认对话框
                    DialogResult result = MessageBox.Show($"确定要删除人员 \"{EMPNAME}\" 吗？",
                                                          "删除确认",
                                                          MessageBoxButtons.YesNo,
                                                          MessageBoxIcon.Question,
                                                          MessageBoxDefaultButton.Button2);

                    // 用户确认删除
                    if (result == DialogResult.Yes)
                    {
                        // 显示正在处理的提示
                        Cursor = Cursors.WaitCursor;
                        string action = "WareHouse/EMP/UpdateDelete?Id=" + EmpID;
                        string json = await HttpClientHelper.RequestUrl(RequestType.Delete, action, null);// await APIClient.CallApiAsync(action, HttpMethod.POST);
                        ApiPaging<int> model = JsonConvert.DeserializeObject<ApiPaging<int>>(json);
                        // 如果操作成功，刷新数据
                        if (model.Code == ApiEnums.Success)
                        {
                            // 重新加载数据
                            LoadData();
                        }
                        else
                        {
                            MessageBox.Show(model.Message, "操作失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                        // 恢复光标
                        Cursor = Cursors.Default;
                    }
                }
                else
                {
                    MessageBox.Show("请先选择要删除的货架", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                MessageBox.Show("删除操作失败：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void Update_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            try
            {
                // 检查是否有选中的行
                if (gridView1.FocusedRowHandle >= 0)
                {
                    // 显示等待光标
                    Cursor = Cursors.WaitCursor;

                    try
                    {
                        // 获取当前选中行的数据
                        var focusedRow = gridView1.GetFocusedRow();
                        if (focusedRow == null)
                        {
                            MessageBox.Show("无法获取选中行的数据", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return;
                        }

                        string empName = focusedRow.GetType().GetProperty("EMPName")?.GetValue(focusedRow)?.ToString() ?? "未命名员工";

                        Form_AddEmp from = new Form_AddEmp();
                        from.UpdateType = false;

                        // 创建emp对象并填充数据
                        EMP emp = new EMP();

                        // 设置员工信息 - 使用反射或类型转换获取属性值
                        foreach (var prop in focusedRow.GetType().GetProperties())
                        {
                            var value = prop.GetValue(focusedRow);
                            switch (prop.Name)
                            {
                                case "EMPID":
                                    emp.EMPID = value?.ToString() ?? string.Empty;
                                    break;
                                case "EMPName":
                                    emp.EMPName = value?.ToString() ?? string.Empty;
                                    break;
                                case "EMpEmail":
                                    emp.EMpEmail = value?.ToString() ?? string.Empty;
                                    break;
                                case "IdCard":
                                    emp.IdCard = value?.ToString() ?? string.Empty;
                                    break;
                                case "DEPCODE":
                                    emp.DEPCODE = value?.ToString() ?? string.Empty;
                                    break;
                                case "DEPNAME":
                                    emp.DEPNAME = value?.ToString() ?? string.Empty;
                                    break;
                                case "JobCode":
                                    emp.JobCode = value?.ToString() ?? string.Empty;
                                    break;
                                case "JobName":
                                    emp.JobName = value?.ToString() ?? string.Empty;
                                    break;
                                case "CreatedBy":
                                    emp.CreatedBy = value?.ToString() ?? string.Empty;
                                    break;
                                case "CreatedTime":
                                    if (value != null)
                                        emp.CreatedTime = Convert.ToDateTime(value);
                                    break;
                                case "Phone":
                                    if (value != null)
                                        emp.Phone = value?.ToString() ?? string.Empty;
                                    break;
                                case "IsEnable":
                                    if (value != null)
                                        emp.IsEnable =  Convert.ToBoolean(value);
                                    break;
                                case "UpdatedTime":
                                    if (value != null)
                                        emp.UpdatedTime = Convert.ToDateTime(value);
                                    break;
                            }
                        }

                        // 传递emp对象到编辑窗体
                        from.Current = emp;

                        // 恢复光标
                        Cursor = Cursors.Default;

                        // 显示编辑窗体
                        if (from.ShowDialog() == DialogResult.OK)
                        {
                            // 编辑成功后刷新数据
                            Clear();
                        }
                    }
                    catch (FormatException fex)
                    {
                        MessageBox.Show("数据格式错误：" + fex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    MessageBox.Show("请先选择要修改的员工", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                MessageBox.Show("修改操作失败：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                // 确保光标恢复正常
                Cursor = Cursors.Default;
            }
        }

        private void gridView1_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            try
            {
                // 检查是否点击了按钮列且有选中的行
                if (e.RowHandle >= 0)
                {
                    var rowData = gridView1.GetRow(e.RowHandle);
                    if (rowData == null)
                    {
                        return;
                    }
                    
                    // 获取数据使用反射
                    var rowType = rowData.GetType();
                    
                    // 检查是否点击了启用/禁用按钮列
                    if (e.Column.FieldName == "IsEnable")
                    {
                        EMP model = new EMP();
                        model.EMPID = rowType.GetProperty("EMPID")?.GetValue(rowData)?.ToString();
                        model.EMPName = rowType.GetProperty("EMPName")?.GetValue(rowData)?.ToString() ?? "未命名员工";
                        bool currentState = rowType.GetProperty("IsEnable") != null && 
                                          rowType.GetProperty("IsEnable").GetValue(rowData) != null && 
                                          Convert.ToBoolean(rowType.GetProperty("IsEnable").GetValue(rowData));
                        string newState = !currentState ? "启用" : "禁用";
                        model.IsEnable = !currentState;
                        model.EMpEmail= rowType.GetProperty("EMpEmail")?.GetValue(rowData)?.ToString();
                        model.IdCard= rowType.GetProperty("IdCard")?.GetValue(rowData)?.ToString();
                        model.Phone= rowType.GetProperty("Phone")?.GetValue(rowData)?.ToString();
                        // 显示确认对话框
                        DialogResult result = MessageBox.Show($"确定要{newState}员工 \"{model.EMPName}\" 吗？",
                                                         $"{newState}确认",
                                                         MessageBoxButtons.YesNo,
                                                         MessageBoxIcon.Question,
                                                         MessageBoxDefaultButton.Button2);

                        // 用户确认操作
                        if (result == DialogResult.Yes && !string.IsNullOrEmpty(model.EMPID))
                        {
                            // 显示正在处理的提示
                            Cursor = Cursors.WaitCursor;

                            // 调用API更新启用状态
                            UpdateEmployeeEnableStatus(model);
                        }
                    }
                    // 如果点击了编辑按钮列
                    //else if (e.Column.FieldName == "EditColumn")
                    //{
                    //    // 调用更新方法
                    //    DevExpress.XtraEditors.Controls.ButtonPressedEventArgs args = 
                    //        new DevExpress.XtraEditors.Controls.ButtonPressedEventArgs(null);
                    //    Update_ButtonClick(null, args);
                    //}
                    //// 如果点击了删除按钮列
                    //else if (e.Column.FieldName == "DeleteColumn")
                    //{
                    //    // 调用删除方法
                    //    DevExpress.XtraEditors.Controls.ButtonPressedEventArgs args = 
                    //        new DevExpress.XtraEditors.Controls.ButtonPressedEventArgs(null);
                    //    DeleteBtn_ButtonClick(null, args);
                    //}
                }
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                MessageBox.Show("操作失败：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                // 确保光标恢复正常
                Cursor = Cursors.Default;
            }
        }
        
        /// <summary>
        /// 更新员工启用状态
        /// </summary>
        /// <param name="empId">员工ID</param>
        private async void UpdateEmployeeEnableStatus(EMP emp)
        {
            try
            {
                // 构建API请求
                string action = $"WareHouse/EMP/UpdateEnable";
                string json = await HttpClientHelper.RequestUrl(RequestType.Put, action, JsonConvert.SerializeObject(emp));
                ApiPaging<int> model = JsonConvert.DeserializeObject<ApiPaging<int>>(json);
                
                // 处理API响应
                if (model.Code == ApiEnums.Success)
                {
                    string stateText = emp.IsEnable ? "启用" : "禁用";
                    MessageBox.Show($"员工{stateText}成功！", "操作成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    // 重新加载数据
                    LoadData();
                }
                else
                {
                    MessageBox.Show(model.Message, "操作失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("更新员工状态失败：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                // 恢复光标
                Cursor = Cursors.Default;
            }
        }

        private void Enable_QueryCheckStateByValue(object sender, DevExpress.XtraEditors.Controls.QueryCheckStateByValueEventArgs e)
        {
            string val = "";
            if (e.Value != null)
            {
                val = e.Value.ToString();
            }
            else
            {
                val = "False";//默认为不选   
            }
            switch (val)
            {
                case "True":
                case "Yes":
                case "1":
                    e.CheckState = CheckState.Checked;
                    break;
                case "False":
                case "No":
                case "0":
                    e.CheckState = CheckState.Unchecked;
                    break;
                default:
                    e.CheckState = CheckState.Unchecked;//初始化就是不选
                    break;
            }
            e.Handled = true;
        }
    }
}